#include "datareader.h"

DataReader::DataReader(const SerialConfig &config,QObject *parent) : QObject(parent),
    m_config(config), m_serialPort(new QSerialPort(this))
{
    m_pSqliteManage = new SqliteManage;
    // 连接数据库
    if (!m_pSqliteManage->openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        //QMessageBox::critical(this, "错误", "数据库连接失败：" + m_pSqliteManage->lastError());
    }
    // 配置串口
    m_serialPort->setPortName(m_config.portName);
    m_serialPort->setBaudRate(m_config.baudRate);
    m_serialPort->setDataBits(m_config.dataBits);
    m_serialPort->setParity(m_config.parity);
    m_serialPort->setStopBits(m_config.stopBits);
    m_serialPort->setFlowControl(m_config.flowControl);

    // 连接串口信号
    connect(m_serialPort, &QSerialPort::readyRead, this, &DataReader::readData);
    connect(m_serialPort, QOverload<QSerialPort::SerialPortError>::of(&QSerialPort::error),
            this, &DataReader::handleError);
}

DataReader::~DataReader()
{
    stopReading();
}

bool DataReader::startReading(){
    if (m_serialPort->isOpen())
        return true;

    if (m_serialPort->open(QIODevice::ReadOnly)) {
        qDebug() << "串口已打开:" << m_config.portName;
        return true;
    } else {
        qDebug() << "无法打开串口:" << m_config.portName << m_serialPort->errorString();
        return false;
    }
}

void DataReader::stopReading(){
    if (m_serialPort->isOpen()) {
        m_serialPort->close();
        qDebug() << "串口已关闭:" << m_config.portName;
    }
}

SerialConfig DataReader::config() const
{
    return m_config;
}

void DataReader::readData()
{
    static QByteArray buffer;
    buffer.append(m_serialPort->readAll());
    // 数据格式为: "L:1200,T:25.5,H:60.2\n"
    while (buffer.contains('\n')) {
        int pos = buffer.indexOf('\n');
        QByteArray line = buffer.left(pos);
        buffer = buffer.mid(pos + 1);
        // 解析数据
        parseData(line);
    }
}

void DataReader::parseData(const QByteArray &data)
{
    static qreal x = 0;
    // 简单解析示例，实际应用中需根据实际数据格式调整
    // 格式: "L:1200,T:25.5,H:60.2"
    DataPoint point;
    point.x = x;
    // 解析光照
    QRegularExpression re("L:(\\d+(\\.\\d+)?)");
    QRegularExpressionMatch match = re.match(data);
    if (match.hasMatch())
        point.light = match.captured(1).toDouble();
    else
        point.light = 0;
    // 解析温度
    re.setPattern("T:(-?\\d+(\\.\\d+)?)");
    match = re.match(data);
    if (match.hasMatch())
        point.temperature = match.captured(1).toDouble();
    else
        point.temperature = 0;
    // 解析湿度
    re.setPattern("H:(\\d+(\\.\\d+)?)");
    match = re.match(data);
    if (match.hasMatch())
        point.humidity = match.captured(1).toDouble();
    else
        point.humidity = 0;
    // 发送数据
    emit dataReady(point);

    if (m_pSqliteManage && m_config.id > 0) {
        bool success = m_pSqliteManage->insertSensorData(
            m_config.device_id,
            point.temperature,
            point.humidity,
            point.light
        );

        if (success) {
            emit dataStored(m_config.id, point);
        } else {
            qDebug() << "Failed to store data for device" << m_config.id;
        }
    }
    x += 0.5;
}

void DataReader::handleError(QSerialPort::SerialPortError error)
{
    if (error != QSerialPort::NoError) {
        emit errorOccurred(m_serialPort->errorString());
        qDebug() << "串口错误:" << m_serialPort->errorString();
    }
}



